import 'dart:async';

import 'package:demo/app/routes/app_pages.dart';
import 'package:demo/app/widgets/CommonDialog.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../../model/config_model.dart';
import '../../../net/api_provider.dart';
import '../../../theme/app_text_theme.dart';
import '../../../utils/sp_util.dart';
import '../../global.dart';
import 'package:permission_handler/permission_handler.dart';


class SplashController extends GetxController with StateMixin<Config> {

  var platform =  const MethodChannel("sing.top/rth");

  @override
  void onReady() {
    super.onReady();
    platform.setMethodCallHandler(flutterMethod);

    var isFirst = SpUtil.read(SpUtil.IS_FIRST,true);
    Future.delayed(const Duration(milliseconds: 300), () { // 这里做个延时，某些机型上可能ScreenUtil没初始化好导致弹窗空白
      if(isFirst){
        showDialog();
      }else{
        agreeAuth();
      }
    });
  }
  // 弹窗
  void showDialog() {
    Get.dialog(
      CommonDialog(
          canCancel: false,
          contentWidget:getContent(),
          yesStr: '同意',
          noStr: '拒绝',
          noFun: () => SystemNavigator.pop(),
          yesFun: ()=> agreeAuth()
      ),
    );
  }

  // 同意授权
  Future<void> agreeAuth()  async {
    SpUtil.write(SpUtil.IS_FIRST,false);

    if(GetPlatform.isAndroid){
      if(Global.CHANNEL=='APP001'){
        PermissionStatus permissionStatus = await checkPermission(); // 检查权限
        if (permissionStatus.isDenied) {// 权限被拒绝，请求权限
          permissionStatus = await requestPermission();
        }
        if (permissionStatus.isGranted) {// 权限被授予，可以进行下一步操作
          var imei = await platform.invokeMethod('getImei');
          SpUtil.write(SpUtil.IMEI,imei);
        } else if (permissionStatus.isRestricted || permissionStatus.isDenied) {// 权限受限或被拒绝，可以引导用户去系统设置修改
          SpUtil.write(SpUtil.IMEI,'');
        }
        print('imei = ${SpUtil.read(SpUtil.IMEI,'')}');
      }

      var oaid = await platform.invokeMethod('getOaid');
      SpUtil.write(SpUtil.OAID,oaid);
      print('oaid = ${SpUtil.read(SpUtil.OAID,'')}');

      Map<String, dynamic> jsonObject = {};
      jsonObject['is_test_url'] = SpUtil.read(SpUtil.IS_TEST_URL, false);// 是否是测试线
      var netParams = await platform.invokeMethod('getNetParams',jsonObject);
      SpUtil.write(SpUtil.NET_PARAMS,'$netParams&channel_code=${Global.CHANNEL}');
      print(netParams);

      platform.invokeMethod('loadAd');
    }else if(GetPlatform.isIOS){
      var netParams = await platform.invokeMethod('getNetParams');
      SpUtil.write(SpUtil.NET_PARAMS,'$netParams&channel_code=${Global.CHANNEL}');
      print(netParams);

      platform.invokeMethod('loadAd');
    }else{
      EasyLoading.showToast('没有开发呢');
    }
  }

  // 检查权限状态
  Future<PermissionStatus> checkPermission() async {
    PermissionStatus permissionStatus = await Permission.phone.status;
    return permissionStatus;
  }
  // 请求权限
  Future<PermissionStatus> requestPermission() async {
    PermissionStatus permissionStatus = await Permission.phone.request();
    return permissionStatus;
  }

// 内容
  Widget getContent(){
    return RichText(
      text: TextSpan(
        style: text_131732_14,
        children: [
          TextSpan(text: '尊敬的用户：\n\n欢迎使用${Global.APP_NAME}！在使用我们的产品和服务前，请你先阅读并同意'),
          TextSpan(
              text: "《用户协议》",
              style: text_main_14b,
              recognizer: TapGestureRecognizer()..onTap = () {
                var map = {
                  'title': Global.agreementUserTitle,
                  'url': Global.getAgreementUser(),
                };
                Get.toNamed(Routes.H5_WEBVIEW, parameters: map);
              }),
          const TextSpan(text: '和'),
          TextSpan(
            text: "《隐私保护政策》",
            style: text_main_14b,
            recognizer: TapGestureRecognizer()
              ..onTap = (){
                var map = {
                  'title': Global.agreementPolicyTitle,
                  'url': Global.getAgreementPolicy(),
                };
                Get.toNamed(Routes.H5_WEBVIEW, parameters: map);
              },
          ),
          const TextSpan(text: "，以帮助你了解我们为你提供的服务及处理个人信息的方式。\n\n点击“同意”按钮代表你已同意签署协议及以上约定。")
        ],
      ),
    );
  }

  Future<dynamic> flutterMethod(MethodCall methodCall) async {
    switch (methodCall.method) {
      case 'getOaid':
        String data = methodCall.arguments as String; // 接收来自原生代码的数据
        print('flutter 打印：$data');
        break;
      case 'getImei':
        String data = methodCall.arguments as String; // 接收来自原生代码的数据
        print('flutter 打印：$data');
        break;
      case 'loadAdOver':
        String data = methodCall.arguments as String; // 接收来自原生代码的数据
        print('loadAdOver ：$data');

        var result = await apiProvider.getData({}, ApiProvider.app_online);
        if(result.code == 200){
          Global.isAuditing = ((result.data['result'] ?? 0) == 1);
          toNext();
        }else{
          toNext();
        }

        break;
    }
  }

  @override
  void onClose() {
    super.onClose();
    killTimer();
  }

  var str = ''.obs; // 记录倒计时剩余时间

  Timer? _timer; // 倒计时器
  void killTimer() {
    _timer?.cancel(); // 关闭计时器
    _timer = null; // 置空
  }

  // 倒计时方法 time 倒计时时间
  void startCountDown(int time,Function fun) {
    if (_timer != null) {
      killTimer();
    }
    if (time <= 0) {
      fun.call();
      return;
    }

    var countTime = time;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countTime <= 0) {// 倒计时结束
        timer.cancel();
        fun.call();
      } else {
        str.value = '${countTime}s 跳过';
        countTime--;
      }
    });
  }

  ApiProvider apiProvider = Get.find();

  void toNext() {
    var token = SpUtil.read(SpUtil.TOKEN,'');
    print('token = $token');
    if('$token'.isEmpty){
      Get.offNamed(Routes.LOGIN);
    }else{
      var token = SpUtil.read(SpUtil.TOKEN, '');
      var phone = SpUtil.read(SpUtil.PHONE, '');
      var channel_id = SpUtil.read(SpUtil.CHANNEL_ID, -1);
      Map<String, dynamic> jsonObject = {};
      if('$token'.isNotEmpty){
        jsonObject['token'] = token;
      }
      if('$phone'.isNotEmpty){
        jsonObject['phone'] = phone;
      }
      if('$channel_id'.isNotEmpty){
        jsonObject['channel_id'] = channel_id;
      }

      platform.invokeMethod('setData',jsonObject);
      Get.offAllNamed(Routes.MAIN);
    }
  }
}
